/*
 * Copyright 2021-2022 Open Kunlun Technology <https://www.openkunlun.io>
 */

package io.openkunlun.scaladsl.context

import io.openkunlun.scaladsl.context.Context.ContextTag

/**
 * @author ericxin.
 */
class Context(val tags: Seq[ContextTag]) {
  def withTag(key: String, value: String): Context = {
    new Context(tags.filterNot(_.key == key) :+ ContextTag(key, value))
  }
  def withTags(map: Map[String, String]): Context = {
    new Context(tags.filterNot(it => map.contains(it.key)) ++ map.map(it => ContextTag(it._1, it._2)).toSeq)
  }
  def withTags(addTags: Seq[ContextTag]): Context = {
    new Context(tags.filterNot(it => addTags.exists(_.key == it.key)) ++ addTags)
  }

  def get(key: String): Option[String] = {
    tags.find(_.key == key).map(_.value)
  }
}

object Context {
  final case class ContextTag(key: String, value: String)

  def empty: Context = new Context(Seq.empty)
  def of(key: String, value: String): Context = new Context(ContextTag(key, value) :: Nil)
  def of(map: Map[String, String]): Context = new Context(map.map(it => ContextTag(it._1, it._2)).toSeq)
  def of(tags: Seq[ContextTag]): Context = new Context(tags)
}